//
//  MessageCircleMemberViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/2/7.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import Networking
import Alamofire
import PKHUD
import SwiftyJSON

class MessageCircleMemberViewController: BaseViewController, ImageFactory, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource, AddCornerUIRectCorner,SearchUserTableViewCellDelegate {
    
    @IBOutlet weak var mainTableView: UITableView!
    let headerHeight: CGFloat = 64
    let cellHeight: CGFloat = 80
    let footerHeight: CGFloat = 50
    var page:Int = 0
    var totalPage:Int = 0
    
    var data: [circleMemberListModel] = []
    var circieId: String?
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        // Do any additional setup after loading the view.
        self.fetchCircleList(parameters: ["page":page,"pageSize":10, "circleId": circieId ?? "1"])
    }
    
    func setUI() {
         mainTableView.register(UINib(nibName: "\(SearchUserTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "cell")
        mainTableView.layoutIfNeeded()
        mainTableView.tableHeaderView = setHeaderView()
        mainTableView.tableFooterView = setFooterView()
    }
    
    func setHeaderView() -> UIView {
        let headerView = BaseCircleView()
        headerView.frame = CGRect(x: 0, y: 0, width: mainTableView.width, height: headerHeight)
        headerView.backgroundColor = UIColor.white
        addCornerWithView(aView: headerView, aCorners: [.topLeft, .topRight]
            , aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        
        setSearchBar(mainView: headerView)
        return headerView
    }
    
    func setSearchBar(mainView: BaseCircleView) {
        let searchBar = UISearchBar()
        searchBar.frame = CGRect(x: 10, y: 20, width: ScreenWidth - 40, height: 28)
        searchBar.delegate = self
        searchBar.barStyle = .blackTranslucent
        let searchImage = createImage(color: UIColor(hex: 0xBFBFBF), height: 28)
        searchBar.backgroundImage = searchImage
        searchBar.backgroundColor = UIColor.clear
        searchBar.setSearchFieldBackgroundImage(searchImage, for: .normal)
        searchBar.layer.cornerRadius = searchBar.height / 2
        searchBar.layer.masksToBounds = true
        let searchField = searchBar.value(forKey: "searchField") as? UITextField
        if let textField = searchField {
            textField.layer.cornerRadius = searchBar.height / 2
            textField.layer.masksToBounds = true
            textField.backgroundColor = UIColor.white
            textField.attributedPlaceholder = NSAttributedString(string: "快速查找密友", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14)])
            searchField?.textColor = UIColor.white
             let imageView = UIImageView(image: UIImage(named: "icon_search"))
            imageView.sizeToFit()
            textField.leftView = imageView
        }
        mainView.addSubview(searchBar)
    }
    
    func setFooterView() -> UIView {
        let footerView = UIView()
        footerView.frame = CGRect(x: 0, y: 0, width: ScreenWidth - 20, height: footerHeight)
        footerView.backgroundColor = UIColor.white
        let button = UIButton(frame: CGRect(x: 0, y: 10, width: ScreenWidth - 20, height: 40))
        button.backgroundColor = ONColor.searchButtomColor
        button.setImage(UIImage(named: "bottom_button_ico"), for: .normal)
        footerView.addSubview(button)
        
        self.addCornerWithView(aView: footerView, aCorners: [.bottomLeft,.bottomRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
       
        return footerView
    }
    
    // MARK: - UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? SearchUserTableViewCell
        let model = self.data[indexPath.row]
        cell?.bindData(model: model)
        cell?.delegate = self
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return cellHeight
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let messageCirclePersonalCenterVC = PersonInfoViewController(nibName: "\(PersonInfoViewController.self)", bundle: nil)
        let model = self.data[indexPath.row]
        messageCirclePersonalCenterVC.userId = model.id!
        self.navigationController?.pushViewController(messageCirclePersonalCenterVC, animated: true)
        
    }
    
    /// 获取文章列表
    func fetchCircleList(parameters:[String:Any]) -> Void {
        let requesturl = "\(BaseURL)\(circleList)"
        
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.totalPage = json["data"]["total"].int!
                                        let arr = json["data"]["rows"].array!
                                        for subject in arr{
                                            let dic = subject.dictionary!
                                            var model = circleMemberListModel(fromDic: dic)
                                            
                                            let label = dic["grade"]?.dictionary!
                                            if !(label?.isEmpty)!{
                                                model.initGrade(dic: label!)
                                            }
                        
                                            self.data.append(model)
                                        }
                                        self.mainTableView.reloadData()
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                       
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                               
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    
    /// 关注用户
    func attentionUser(parameters:[String:Any], btn:UIButton) -> Void {
        HUD.show(.label("加载中..."))
        let requesturl = "\(BaseURL)\(attentionUserUrl)"
        
        Alamofire.request(requesturl, method: .post,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        btn.isSelected = true
                                        self.showToast(msg:"关注成功")
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                self.showToast(msg:"关注失败")
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    
    /// 取消关注用户
    func attentionCancelUser(parameters: [String:Any], btn:UIButton) -> Void {
        HUD.show(.label("加载中..."))
        let requesturl = "\(BaseURL)\(attentionCancelUserUrl)"
        Alamofire.request(requesturl, method: .post,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        btn.isSelected = false
                                        self.showToast(msg:"取消关注成功")
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                        
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                self.showToast(msg:"请求失败")
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
}
